package top.dingwen.io.treasure.websocket.core.listener;

import cn.hutool.core.collection.CollUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;
import top.dingwen.io.treasure.websocket.constant.WebSocketConstant;
import top.dingwen.io.treasure.websocket.core.holder.WebSocketSessionHolder;
import top.dingwen.io.treasure.websocket.util.WebSocketUtils;

/**
 * WebSocket 主题订阅监听器
 *
 * @author zendwang
 */
@Slf4j
@Component
public class WebSocketTopicListener implements ApplicationRunner, Ordered {

    /**
     * 在Spring Boot应用程序启动时初始化WebSocket主题订阅监听器
     *
     * @param args 应用程序参数
     */
    @Override
    public void run(ApplicationArguments args) {
        // 订阅WebSocket消息
        WebSocketUtils.subscribeMessage((message) -> {
            log.info("{},{},WebSocket主题订阅收到消息session keys={} message={}",
                    WebSocketConstant.WS_L_O_S,
                    WebSocketConstant.WS_L_TL,
                    message.getSessionKeys(), message.getMessage());
            // 如果key不为空就按照key发消息 如果为空就群发
            if (CollUtil.isNotEmpty(message.getSessionKeys())) {
                message.getSessionKeys().forEach(key -> {
                    if (WebSocketSessionHolder.existSession(key)) {
                        WebSocketUtils.sendMessage(key, message.getMessage());
                    }
                });
            } else {
                WebSocketSessionHolder.getSessionKeysAll().forEach(key -> WebSocketUtils.sendMessage(key, message.getMessage()));
            }
        });
        log.info("{},{},初始化WebSocket主题订阅监听器成功", WebSocketConstant.WS_L_O_S, WebSocketConstant.WS_L_TL);
    }

    @Override
    public int getOrder() {
        return -1;
    }
}
